const CategoryModel = require('../models/category.model');
const { ValidationError } = require('../middleware/error');

class CategoryController {
  // 获取分类列表
  static async getCategories(req, res, next) {
    try {
      const { parent_id } = req.query;
      
      let categories;
      if (parent_id === undefined) {
        // 如果没有指定parent_id，则获取所有分类及其子分类
        categories = await CategoryModel.findWithChildren();
      } else {
        // 如果指定了parent_id，则获取该分类下的直接子分类
        const parentId = parseInt(parent_id);
        if (isNaN(parentId)) {
          throw new ValidationError('参数错误', {
            parent_id: ['父分类ID必须是一个有效的数字']
          });
        }
        categories = await CategoryModel.findAll(parentId);
      }

      res.json({
        data: categories
      });
    } catch (error) {
      next(error);
    }
  }

  // 获取单个分类
  static async getCategory(req, res, next) {
    try {
      const { id_or_slug } = req.params;
      
      let category;
      if (/^\d+$/.test(id_or_slug)) {
        // 如果是数字，则按ID查找
        category = await CategoryModel.findById(parseInt(id_or_slug));
      } else {
        // 否则按slug查找
        category = await CategoryModel.findBySlug(id_or_slug);
      }

      if (!category) {
        throw new ValidationError('分类不存在');
      }

      // 获取子分类
      category.children = await CategoryModel.findAll(category.id);

      res.json({
        data: category
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = CategoryController; 